<template>
  <div class="time-slot-container">
    <div class="page-header">
      <h2>时间段设置</h2>
      <el-button type="primary" @click="handleAdd">
        添加时间段
      </el-button>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="时间段名称">
          <el-input v-model="searchForm.name" placeholder="请输入时间段名称" clearable />
        </el-form-item>
        <el-form-item label="时段">
          <el-select style="width: 100px" v-model="searchForm.period" placeholder="请选择时段" clearable>
            <el-option label="上午" value="MORNING" />
            <el-option label="下午" value="AFTERNOON" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select style="width: 100px" v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%"
      >
        <el-table-column prop="name" label="时间段名称" />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="period" label="时段" width="100">
          <template #default="{ row }">
            {{ row.period === 'MORNING' ? '上午' : '下午' }}
          </template>
        </el-table-column>
        <el-table-column prop="maxVisitors" label="最大预约人数" width="120" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button 
                :type="row.status === 1 ? 'warning' : 'success'" 
                link 
                @click="handleToggleStatus(row)"
              >
                {{ row.status === 1 ? '禁用' : '启用' }}
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :total="page.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加时间段' : '编辑时间段'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="时间段名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入时间段名称" />
        </el-form-item>
        <el-form-item label="时段" prop="period">
          <el-select v-model="formData.period" placeholder="请选择时段">
            <el-option label="上午" value="MORNING" />
            <el-option label="下午" value="AFTERNOON" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" required>
          <div class="time-range">
            <el-time-picker
              v-model="formData.startTime"
              format="HH:mm"
              placeholder="开始时间"
              style="width: 95px"
            />
            <span class="mx-2">至</span>
            <el-time-picker
              v-model="formData.endTime"
              format="HH:mm"
              placeholder="结束时间"
              style="width: 95px"
            />
          </div>
        </el-form-item>
        <el-form-item label="最大人数" prop="maxVisitors">
          <el-input-number
            v-model="formData.maxVisitors"
            :min="1"
            :max="100"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch 
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import { 
  getTimeSlotPage, 
  addTimeSlot, 
  updateTimeSlot, 
  removeTimeSlot,
  updateTimeSlotStatus 
} from '@/api/timeSlot'

// 搜索表单
const searchForm = ref({
  name: '',
  period: '',
  status: ''
})

// 分页参数
const page = ref({
  current: 1,
  size: 10,
  total: 0
})

// 表格数据
const loading = ref(false)
const tableData = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const formData = ref({
  id: '',
  name: '',
  period: 'MORNING',
  startTime: '',
  endTime: '',
  maxVisitors: 20,
  status: 1
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入时间段名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  period: [
    { required: true, message: '请选择时段', trigger: 'change' }
  ],
  maxVisitors: [
    { required: true, message: '请输入最大预约人数', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '人数范围在1-100之间', trigger: 'blur' }
  ]
}

// 获取时间段列表
const fetchTimeSlots = async () => {
  loading.value = true
  try {
    const params = {
      current: page.value.current,
      size: page.value.size,
      name: searchForm.value.name,
      period: searchForm.value.period,
      status: searchForm.value.status
    }
    const res = await getTimeSlotPage(params)
    tableData.value = res.records
    page.value.total = res.total
  } catch (error) {
    ElMessage.error('获取时间段列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value.current = 1
  fetchTimeSlots()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    name: '',
    period: '',
    status: ''
  }
  handleSearch()
}

// 添加时间段
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = {
    id: '',
    name: '',
    period: 'MORNING',
    startTime: '',
    endTime: '',
    maxVisitors: 20,
    status: 1
  }
  dialogVisible.value = true
}

// 编辑时间段
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 创建当天的日期对象作为基准
  const today = new Date()
  const [startHours, startMinutes] = row.startTime.split(':')
  const [endHours, endMinutes] = row.endTime.split(':')
  
  // 设置时间
  const startTime = new Date(today)
  startTime.setHours(startHours, startMinutes, 0)
  
  const endTime = new Date(today)
  endTime.setHours(endHours, endMinutes, 0)
  
  formData.value = {
    ...row,
    startTime,
    endTime
  }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 格式化时间，只保留时分秒
        const submitData = {
          ...formData.value,
          startTime: formData.value.startTime ? dayjs(formData.value.startTime).format('HH:mm:ss') : '',
          endTime: formData.value.endTime ? dayjs(formData.value.endTime).format('HH:mm:ss') : ''
        }

        if (dialogType.value === 'add') {
          await addTimeSlot(submitData)
          ElMessage.success('添加成功')
        } else {
          await updateTimeSlot(submitData)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchTimeSlots()
      } catch (error) {
        ElMessage.error(dialogType.value === 'add' ? '添加失败' : '更新失败')
      }
    }
  })
}

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    await updateTimeSlotStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success('状态更新成功')
    fetchTimeSlots()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 删除时间段
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这个时间段吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await removeTimeSlot(row.id)
      ElMessage.success('删除成功')
      fetchTimeSlots()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 分页大小改变
const handleSizeChange = (val) => {
  page.value.size = val
  fetchTimeSlots()
}

// 当前页改变
const handleCurrentChange = (val) => {
  page.value.current = val
  fetchTimeSlots()
}

// 初始化
fetchTimeSlots()
</script>

<style scoped>
.time-slot-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.search-card {
  margin-bottom: 20px;
}

.mx-2 {
  margin: 0 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.time-range {
  display: flex;
  align-items: center;
  gap: 8px;
}

.time-range :deep(.el-time-picker) {
  width: 95px;
}
</style> 